{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import datetime as dt\n",
    "\n",
    "from dateutil.relativedelta import relativedelta\n",
    "\n",
    "from gs_quant.datetime.date import prev_business_date\n",
    "from gs_quant.instrument import EqOption, OptionType, OptionStyle\n",
    "from gs_quant.markets import PricingContext, HistoricalPricingContext\n",
    "from gs_quant.markets.portfolio import Portfolio\n",
    "from gs_quant.risk import EqDelta, EqGamma, EqVega, EqSpot, DollarPrice\n",
    "from gs_quant.session import Environment, GsSession"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "# external users should substitute their client id and secret; please skip this step if using internal jupyterhub\n",
    "GsSession.use(Environment.PROD, client_id=None, client_secret=None, scopes=('run_analytics',))"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### Create Eq Options Portfolios\n",
    "\n",
    "Let's now create a put-spread and a butterfly using `EqOption`. The underlier is entered as Reuters Instrument Code and \n",
    "can be one of .SPX, .STOXX50E, .FTSE, .N225. \n",
    "Strike can be specified as value, percent or at-the-money e.g. 62.5, 95%, ATM-25, ATMF.\n",
    "Other parameters we can instantiate can be uncovers by pressing `shift+tab` on `EqOption`. "
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "put_1 = EqOption('.SPX', expiration_date = '3m', strike_price = '95%', option_type = OptionType.Put, \n",
    "                 option_style = OptionStyle.European, buy_sell = 'Buy')\n",
    "put_2 = EqOption('.SPX', expiration_date = '3m', strike_price = '105%', option_type = OptionType.Put, \n",
    "                 option_style = OptionStyle.European, buy_sell = 'Sell')\n",
    "put_spread = Portfolio((put_1, put_2))\n",
    "\n",
    "itm_call = EqOption('.SPX', expiration_date = '3m', strike_price = '90%', option_type = OptionType.Call, \n",
    "                    option_style=OptionStyle.European, buy_sell = 'Buy')\n",
    "otm_call = EqOption('.SPX', expiration_date = '3m', strike_price = '110%', option_type = OptionType.Call, \n",
    "                    option_style = OptionStyle.European, buy_sell = 'Buy')\n",
    "atm_call = EqOption('.SPX', expiration_date = '3m', strike_price = 'atm', option_type = OptionType.Call, \n",
    "                    number_of_options = 2, option_style = OptionStyle.European, buy_sell = 'Sell')\n",
    "butterfly = Portfolio((itm_call, otm_call, atm_call))"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### Compute greeks for both our portfolios at inception and at expiry\n",
    "\n",
    "Let's now compute greeks on our portfolios. For an exhaustive list of supported metrics for `EqOption` please refer to \n",
    "the [Measures](https://developer.gs.com/docs/gsquant/guides/Pricing-and-Risk/measures/) guide.\n"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "trade_date = dt.date.today() - relativedelta(months = 3)\n",
    "trade_date = prev_business_date(trade_date)\n",
    "\n",
    "with PricingContext(pricing_date = trade_date):\n",
    "    put_spread.resolve(in_place = True)\n",
    "    ps_greeks = put_spread.calc((EqDelta, EqGamma, EqVega))\n",
    "    butterfly.resolve(in_place = True)\n",
    "    b_greeks = butterfly.calc((EqDelta, EqGamma, EqVega))\n",
    "\n",
    "expiry = prev_business_date(put_1.expiration_date)\n",
    "\n",
    "with PricingContext(pricing_date = expiry):\n",
    "    ps_exp = put_spread.calc((EqDelta, EqGamma, EqVega))\n",
    "    b_exp = butterfly.calc((EqDelta, EqGamma, EqVega))\n",
    "    "
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "print(f'Put Spread Delta at inception: {ps_greeks[EqDelta].aggregate():.0f}')\n",
    "print(f'Put Spread Gamma at inception: {ps_greeks[EqGamma].aggregate():.0f}')\n",
    "print(f'Put Spread Vega at inception: {ps_greeks[EqVega].aggregate():.0f}')\n",
    "\n",
    "print(f'Butterfly Delta at inception: {b_greeks[EqDelta].aggregate():.0f}')\n",
    "print(f'Butterfly Gamma at inception: {b_greeks[EqGamma].aggregate():.0f}')\n",
    "print(f'Butterfly Vega at inception: {b_greeks[EqVega].aggregate():.0f}')"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### Now let's look at our portfolios' PV vs Spot price\n",
    "\n",
    "Using `EqSpot` we can track the performance of the index vs our portfolio."
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "with HistoricalPricingContext(start = trade_date, end = expiry):\n",
    "    ps_perf = put_spread.calc((EqSpot, DollarPrice))\n",
    "    b_perf = butterfly.calc((EqSpot, DollarPrice))\n",
    "    "
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "from pandas.plotting import register_matplotlib_converters\n",
    "register_matplotlib_converters()\n",
    "\n",
    "ps_perf = ps_perf.aggregate()\n",
    "fig, ax1 = plt.subplots(figsize = (10, 6))\n",
    "plt.figure(figsize = (24, 20))\n",
    "color='tab:blue'\n",
    "ax1.set_ylabel('Spot', color = color)\n",
    "ax1.plot(ps_perf[EqSpot], color = color)\n",
    "ax1.set_title('Put Spread')\n",
    "ax2 = ax1.twinx()\n",
    "color = 'tab:orange'\n",
    "ax2.set_ylabel('$PV', color = color)\n",
    "ax2.plot(ps_perf[DollarPrice], color = color)\n",
    "\n",
    "plt.show()"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "b_perf = b_perf.aggregate()\n",
    "fig, ax1 = plt.subplots(figsize=(10, 6))\n",
    "plt.figure(figsize=(24, 20))\n",
    "color='tab:blue'\n",
    "ax1.set_ylabel('Spot', color=color)\n",
    "ax1.plot(b_perf[EqSpot], color=color)\n",
    "ax1.set_title('Butterfly')\n",
    "ax2 = ax1.twinx()\n",
    "color = 'tab:orange'\n",
    "ax2.set_ylabel('$PV', color=color)\n",
    "ax2.plot(b_perf[DollarPrice], color=color)\n",
    "\n",
    "plt.show()"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  }
 ],
 "metadata": {
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  },
  "kernelspec": {
   "name": "python3",
   "language": "python",
   "display_name": "Python 3"
  },
  "pycharm": {
   "stem_cell": {
    "cell_type": "raw",
    "source": [],
    "metadata": {
     "collapsed": false
    }
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}